package controller;

import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/blogDelete")
public class DeleteServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.检查是否登录
        HttpSession httpSession=req.getSession(false);
        if(httpSession==null){
            //会话为空，未登录
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登录");
        }
        User user=(User)httpSession.getAttribute("user");
        if(user==null) {
            //对象不存在
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户不存在");
        }
        //2.获取当前要删除的博客信息
        String para=req.getParameter("blogId");
        if(para==null||"".equals(para)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("博客参数有误");
        }
        BlogDao blogDao=new BlogDao();
       Blog blog=blogDao.selectOne(Integer.parseInt(para));
       if(blog==null){
           resp.setContentType("text/html;charset=utf8");
           resp.getWriter().write("你要删除的博客不存在");
       }
       //判断登录者和作者是不是一致
        if(user.getUserId()!=blog.getAuthorId()){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("没有权限，无法删除");
        }
        blogDao.delete(Integer.parseInt(para));
        //重定向
        resp.sendRedirect("blog_list.html");
    }
}
